//
//  HomeTableViewController.swift
//  SinaWeibo
//
//  Created by Arvin on 15/11/8.
//  Copyright © 2015年 Arvin. All rights reserved.
//

import UIKit
import AFNetworking
import MBProgressHUD

private let HomeStatusCell = "statusCell"

class HomeTableViewController: BaseTableViewController {
    
    // MARK: 刷新数据
    @objc func didRefresh() {
        loadDate()
    }
    
    // 微博数据容器
    var statuses: [Status] = [Status]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        visitorLoginView?.setTextAndIconView("关注一些人，回这里看看有什么惊喜", icon: nil)
        if UserAccountViewModel().userLogin {
            prepareToHome()
        }
    }
    
    private func prepareToHome() {
        // 加载微博数据
        loadDate()
        
        setupUI()
        
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: HomeStatusCell)
        
        // cell自动获取行高, 必须满足三个条件1> 设置预估行高 2> 设置自动获取行高 3> 自上而下的自动布局
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        tableView.tableFooterView = activityView
    }
    
    
    // since_id 最新的微博
    private func loadDate() {
        var maxId: Int = 0
        var sinceId: Int = 0
        // 获取最新微博和旧微博
        if activityView.isAnimating() {
            maxId = statuses.last?.id ?? 0
        } else {
            sinceId = statuses.first?.id ?? 0
        }


        StatusHomeViewModel.loadStatusDate(max_id: maxId, since_id: sinceId) { (statuses) -> () in
            // 这里做两个判断, 一个是判断是否为空或者为0
            if statuses?.count == 0 || statuses == nil {
                if statuses == nil {
                    MBProgressHUD.showError(errorMessage)
                    self.activityView.stopAnimating()
                }
                self.refresh.endRefreshing()
                return
            }
            self.refresh.endRefreshing()
            
            // 将数据回调
            if maxId > 0 {
                self.statuses = self.statuses +  statuses!
                self.activityView.stopAnimating()
            } else if sinceId > 0 {
                self.statuses = statuses! + self.statuses
            } else {
                self.statuses = statuses!
            }
            self.tableView.reloadData()
        }
    }
    // MARK: 设置UI
    private func setupUI() {
        tableView.addSubview(refresh)
        refresh.addTarget(self, action: "didRefresh", forControlEvents: .ValueChanged)
    }
    // MARK: 赖加载
    private lazy var refresh: UIRefreshControl = UIRefreshControl()
    private lazy var activityView: UIActivityIndicatorView = {
        let activ =  UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        activ.frame = CGRectMake(0, 0, 35, 35)
        return activ
    }()
}

extension HomeTableViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses.count ?? 0;
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeStatusCell, forIndexPath: indexPath) as! StatusCell
        if indexPath.item == ((statuses.count) - 1) && !activityView.isAnimating() {
            activityView.startAnimating()
            loadDate()
        }
        
        cell.status = self.statuses[indexPath.row]
        
        return cell
    }
    
}